package com.proxy.jdkProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * ecs
 *
 * @Title: com.proxy.jdkProxy
 * @Date: 2020/3/22 15:47
 * @Author: wfg
 * @Description:
 * @Version:
 */
public class ProxyFactory {

    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    /**
     * public static Object newProxyInstance(ClassLoader loader,
     *                                           Class<?>[] interfaces,
     *                                           InvocationHandler h)
     *
     * loader :当前目标对象的类加载器
     * interfaces: 当前目标对象实现的接口类型,使用泛型确定接口类型
     * InvocationHandler: 事情处理,当目标对象被执行是会调用invoke 方法
     * @return
     */

    public Object getProxyFactoryInstatince(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("代理方法执行开始");
                        Object returnObj = method.invoke(target,args);
                        System.out.println("代理对象执行结束");
                        return returnObj;
                    }
                });
    }
}
